package com.example.ywr.repository;

import com.example.ywr.entity.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 订单数据访问层
 */
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {

    /**
     * 根据订单编号查询订单
     */
    Optional<Order> findByOrderNoAndIsDeletedFalse(String orderNo);

    /**
     * 根据用户ID查询订单
     */
    Page<Order> findByUserIdAndIsDeletedFalse(Long userId, Pageable pageable);

    /**
     * 根据订单状态查询订单
     */
    Page<Order> findByStatusAndIsDeletedFalse(Integer status, Pageable pageable);

    /**
     * 根据用户ID和订单状态查询订单
     */
    Page<Order> findByUserIdAndStatusAndIsDeletedFalse(Long userId, Integer status, Pageable pageable);

    /**
     * 根据创建时间范围查询订单
     */
    Page<Order> findByCreateTimeBetweenAndIsDeletedFalse(LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);

    /**
     * 更新订单状态
     */
    @Modifying
    @Query("UPDATE Order o SET o.status = ?2 WHERE o.id = ?1")
    int updateStatus(Long id, Integer status);

    /**
     * 批量更新订单状态
     */
    @Modifying
    @Query("UPDATE Order o SET o.status = ?2 WHERE o.id IN ?1")
    int batchUpdateStatus(List<Long> ids, Integer status);
}